<template>
  <ElDialog
    v-model="dialogVisible"
    :title="dialogType === 'add' ? '添加用户' : '编辑用户'"
    width="30%"
    align-center
  >
    <ElForm ref="formRef" :model="formData" :rules="rules" label-width="80px">
      <ElFormItem label="头像" prop="avatar">
        <ImageSelector v-model="formData.image" :multiple="false" />
      </ElFormItem>
      <!-- <ElFormItem label="图片集" prop="images">
        <ImageSelector v-model="formData.images" :multiple="true" />
      </ElFormItem> -->
      <ElFormItem label="用户名" prop="username">
        <ElInput v-model="formData.username" placeholder="请输入用户名" />
      </ElFormItem>
      <ElFormItem label="密码" prop="password">
        <ElInput v-model="formData.password" placeholder="请输入密码" />
      </ElFormItem>
      <ElFormItem label="状态" prop="status">
        <ElSelect v-model="formData.status">
          <ElOption label="正常" value="1" />
          <ElOption label="冻结" value="0" />
        </ElSelect>
      </ElFormItem>
      <ElFormItem label="角色" prop="role">
        <ElSelect v-model="formData.role" multiple>
          <ElOption
            v-for="role in roleList"
            :key="role.code"
            :value="role.name"
            :label="role.name"
          />
        </ElSelect>
      </ElFormItem>
    </ElForm>
    <template #footer>
      <div class="dialog-footer">
        <ElButton @click="dialogVisible = false">取消</ElButton>
        <ElButton type="primary" @click="handleSubmit">提交</ElButton>
      </div>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
  import { fetchGetRoleList, addUserApi, editUserApi } from '@/api/system-manage'
  import type { FormInstance, FormRules } from 'element-plus'
  import ImageSelector from '@/components/image-selector/index.vue'

  interface Props {
    visible: boolean
    type: string
    userData?: Partial<Api.SystemManage.UserListItem>
  }

  interface Emits {
    (e: 'update:visible', value: boolean): void
    (e: 'submit'): void
  }

  const props = defineProps<Props>()
  const emit = defineEmits<Emits>()

  // 角色列表数据
  const roleList = ref<Api.SystemManage.RoleListItem[]>([])
  const roleListLoaded = ref(false)
  onMounted(async () => {
    try {
      const res: any = await fetchGetRoleList({})
      let arr = res.data
      // 只取角色数组，避免类型报错
      let roleArr: any[] = []
      if (arr && Array.isArray(arr.data)) {
        roleArr = arr.data
      } else if (Array.isArray(arr)) {
        roleArr = arr
      }
      roleList.value = roleArr
      roleListLoaded.value = true
      // 打印角色列表
      // console.log('roleList.value', roleList.value)
    } catch {
      ElMessage.error('角色列表加载失败')
    }
  })

  // 对话框显示控制
  const dialogVisible = computed({
    get: () => props.visible,
    set: (value) => emit('update:visible', value)
  })

  const dialogType = computed(() => props.type)

  // 表单实例
  const formRef = ref<FormInstance>()

  // 表单数据
  const formData = reactive({
    id: '', // 新增 id 字段，解决类型错误
    image: '',
    // images: '', // 多图片字段
    username: '',
    password: '',
    status: '',
    role: [] as string[]
  })

  // 表单验证规则
  const rules: FormRules = {
    username: [
      { required: true, message: '请输入用户名', trigger: 'blur' },
      { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
    ],
    // password: [
    //   { required: true, message: '请输入密码', trigger: 'blur' },
    //   { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
    // ],
    status: [{ required: true, message: '请选择状态', trigger: 'blur' }],
    role: [{ required: true, message: '请选择角色', trigger: 'blur' }]
  }

  /**
   * 初始化表单数据
   * 根据对话框类型（新增/编辑）填充表单
   */
  const initFormData = () => {
    const isEdit = props.type === 'edit' && props.userData
    const row = props.userData

    let roleArr: string[] = []
    if (isEdit && row && Array.isArray(row.role)) {
      // 用 title 字段（中文名）对比，严格映射为 name（英文标识），未匹配到的丢弃
      roleArr = row.role
        .map((r) => {
          const found = roleList.value.find((item) => item.name.trim() === String(r).trim())
          return found ? found.name : undefined
        })
        .filter((v): v is string => !!v)
      Object.assign(formData, {
        id: isEdit && row ? row.id || '' : '',
        username: isEdit && row ? row.username || '' : '',
        status: isEdit && row ? String(row.status ?? '1') : '1',
        role: isEdit && row ? roleArr : [],
        image: isEdit && row ? row.image || '' : ''
      })
    } else {
      Object.assign(formData, {
        id: '',
        username: '',
        password: '',
        status: '1',
        role: [] as string[],
        image: ''
      })
    }
  }

  /**
   * 监听对话框状态变化
   * 当对话框打开时初始化表单数据并清除验证状态
   */
  watch(
    () => [props.visible, props.type, props.userData],
    ([visible]) => {
      if (visible) {
        initFormData()
        nextTick(() => {
          formRef.value?.clearValidate()
        })
      }
    },
    { immediate: true }
  )

  /**
   * 提交表单
   * 验证通过后触发提交事件
   */
  const handleSubmit = async () => {
    if (!formRef.value) return
    await formRef.value.validate(async (valid) => {
      if (valid) {
        const roleIds = formData.role.map((name) => {
          const found = roleList.value.find((item) => item.name === name)
          return found ? found.id : name
        })
        let submitData: any = { ...formData, role: roleIds }
        if (dialogType.value === 'edit') {
          submitData = { ...submitData, id: formData.id }
        } else {
          // 添加时不传 id 字段
          delete submitData.id
        }
        if (dialogType.value === 'add') {
          await addUserApi(submitData)
          ElMessage.success('添加成功')
        } else {
          await editUserApi(submitData)
          ElMessage.success('更新成功')
        }
        dialogVisible.value = false
        emit('submit') // 父组件监听 submit 事件后刷新列表
      }
    })
  }
</script>
